// packageC/hotel/release-demand/release-demand.js
const app = getApp()
import { formatDate } from '../../../utils/util'
import WxValidate from '../../../utils/WxValidate'
const hotelStarColumns = [
  { value: 2, text: '二星及以下/经济型' },
  { value: 3, text: '三星/舒适' },
  { value: 4, text: '四星/高档' },
  { value: 5, text: '五星/豪华' },
  { value: 6, text: '六星' },
  { value: 7, text: '七星' },
  { value: 8, text: '八星' },
  { value: 0, text: '不限' }
]
const roomTypeColumns = [ 
  { value: 1, text: '大床房' },
  { value: 2, text: '双床房' },
  { value: 3, text: '套房' },
  { value: 4, text: '复式套间' }
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      username: '',
      mobile: '',
      start_check_in_time: '',
      end_check_in_time: '',
      checkInDays: 0,
      room_type: '',
      roomTypeText: '',
      room_num: 1,
      expected_price: '',
      hotelPlaceValue: '',
      province_name: '',
      city_name: '',
      district_name: '',
      street_name: '',
      street_id: '',
      hotelStarText: '',
      star_rated: '',
      know: 0
    },
    checkInTimeShow: false,
    checkInTimeValue: '',
    // chooseRoomTypeShow: false,
    roomTypeColumns,
    hotelStarColumns,
    startDay: null,
    tomorrow: null,
    endDay: null,
    hotelPlaceShow: false,
    hotelPlaceOptions: [],
    streetList: [],
    streetShow: false,
    selectStreetID: '',
    selectStreetName: '',
    temPlace: {
      showText: '',
      provinceName: '',
      cityName: '',
      districtName: '',
      streetName: '',
      streetID: '',
    },
    loading: false
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 入住时间选择确认
   * @param {Object} e 
   */
  checkInTimeConfirm: function(e) {
    const start = e.detail[0]
    const end = e.detail[1]
    const startStr = formatDate(start)
    const endStr = formatDate(end)
    const day = (end - start)/1000/60/60/24
    const checkInTimeValue = `${startStr}~${endStr}(${day}天)`
    this.setData({
      'formData.checkInDays': day,
      'formData.start_check_in_time': startStr,
      'formData.end_check_in_time': endStr,
      checkInTimeValue,
      checkInTimeShow: false
    })
  },

  /**
   * 房间类型选择确认
   * @param {Object} e 
   */
  roomTypeConfirm: function(e) {
    const { value, text } = e.detail.value
    this.setData({
      'formData.room_type': value,
      'formData.roomTypeText': text,
      chooseRoomTypeShow: false
    })
  },

  /**
   * 出行城市选择结束
   * @param {Object} e 
   */
  chooseHotelPlaceFinish: function(e) {
    const { selectedOptions, value } = e.detail
    let fieldValue = `${selectedOptions[0].text}-${selectedOptions[1].text}-${selectedOptions[2].text}-`
    this.setData({
      // 选中的省/市/区暂存至temPlace
      'temPlace.provinceName': selectedOptions[0].text,
      'temPlace.cityName': selectedOptions[1].text,
      'temPlace.districtName': selectedOptions[2].text,
      // 页面显示的内容
      'temPlace.showText': fieldValue,
      hotelPlaceShow: false
    })
    this.getStreetList(value)
  },

  /**
   * 根据选中的区/县code获取街道列表
   * @param {String} code 区/县code
   */
  getStreetList: function(code) {
    let urlStr = app.getNetAddresss('platformApplet.address.getAddress')
    urlStr += "&parentid=" + code
    urlStr += "&level_type=street"
    const _this = this
    wx.showLoading({ title: '加载中...' })
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({
            streetList: resData.data,
            streetShow: true
          })
          // 获取到的列表里是否包含已经选中过的街道
          const { formData } = _this.data
          const { street_id, street_name } = formData
          if (street_id) {
            const isSome = resData.data.some(item => item.id == street_id)
            _this.setData({
              selectStreetName: isSome ? street_name : '',
              selectStreetID: isSome ? street_id : ''
            })
          }
        } else {
          app.tips(resData.msg || '加载街道数据失败！')
          // 未选择过街道，则清空所有地址选择
          if (!_this.data.temPlace.streetName) {
            _this.clearPlace()
          }
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 清空酒店地址相关选择
   */
  clearPlace: function() {
    this.setData({
      'formData.province_name': '',
      'formData.city_name': '',
      'formData.district_name': '',
      'formData.hotelPlaceValue': '',
      'formData.street_name': '',
      'temPlace.provinceName': '',
      'temPlace.cityName': '',
      'temPlace.districtName': '',
      'temPlace.showText': '',
      'temPlace.street_name': '',
      selectStreetID: '',
      selectStreetName: ''
    })
  },

  /**
   * 街道选中确认
   */
  streetConfirm: function() {
    const { selectStreetName, selectStreetID } = this.data
    if (!selectStreetName) {
      app.tips('请选择街道！')
      return
    }
    // 页面酒店地址显示拼接街道名称
    let { showText, provinceName, cityName, districtName } = this.data.temPlace
    showText += selectStreetName
    this.setData({
      'formData.province_name': provinceName,
      'formData.city_name': cityName,
      'formData.district_name': districtName,
      'formData.street_name': selectStreetName,
      'formData.street_id': selectStreetID,
      'formData.hotelPlaceValue': showText,
      streetShow: false
    })
  },

  /**
   * 取消街道选择
   */
  streetCancel:function() {
    if(!this.data.formData.street_id) {
      this.clearPlace()
    }
    const { selectStreetID, formData } = this.data
    const { street_id, street_name } = formData
    if (selectStreetID != street_id) {
      this.setData({
        selectStreetID: street_id,
        selectStreetName: street_name
      })
    }
    this.setData({ streetShow: false })
  },

  /**
   * 街道点击选中
   * @param {Object}} e 
   */
  streetSelected: function(e) {
    const { id, areaname } = e.currentTarget.dataset.item
    this.setData({
      selectStreetID: id,
      selectStreetName: areaname
    })
  },

  /**
   * 期望价格只能输入数字
   * @param {Object} e 
   */
  expectPriceInput: function(e) {
    let value = e.detail
    value = value.replace(/\D/g, '')
    this.setData({
      'formData.expected_price': value
    })
  },

  /**
   * 房间类型选择确认
   * @param {Object} e 
   */
  hotelStarConfirm: function(e) {
    const { value, text } = e.detail.value
    this.setData({
      'formData.hotelStarText': text,
      'formData.star_rated': value,
      chooseHotelStarShow: false
    })
  },

  /**
   * 选中知晓
   * @param {Object} e 
   */
  knowChange: function(e) {
    this.setData({
      'formData.know': this.data.formData.know ? 0 : e.detail
    })
  },

  /**
   * 取消寻找导游
   */
  goBack: function() {
    wx.navigateBack({delta: -1})
  },

  /**
   * 发布需求
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    const urlStr = app.getNetAddresss('plugin.hotel.frontend.hotel.hotelDemand.add')
    const _this = this
    wx.showLoading({ title: '加载中...' })
    this.setData({ loading: true })
    app._postNetWork({
      url: urlStr,
      data: this.data.formData,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '需求发布成功！',
            showCancel: false,
            complete: (resC) => {
              if (resC.confirm) {
                const { tmplIds } = app.data
                wx.requestSubscribeMessage({
                  tmplIds: tmplIds[0],
                  complete: function() {
                    const pages = getCurrentPages()
                    //获取上一个页面的实例
                    const beforePage = pages[pages.length - 2]
                    //1、调用上一个页面onLoad
                    beforePage.onLoad() 
                    //2、调用上一个页面刷新方法
                    beforePage.refreshPage()
                    wx.navigateBack({ delta: -1 })
                  }
                })
              }
            }
          })
        } else {
          app.tips(resData.msg || '提交失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ loading: false })
      }
    })
  },

  /**
   * 获取省市列表(酒店地点)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const province = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                return {
                  text: item2.areaname,
                  value: item2.id + ''
                }
              })
              return {
                text: item1.areaname,
                value: item1.id + '',
                children: child2
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ hotelPlaceOptions: province})
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      username: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
      checkInDays: {
        min: 1
      },
      room_type: {
        required: true
      },
      expected_price: {
        required: true,
        min: 1
      },
      street_id: {
        required: true
      },
      star_rated: {
        required: true
      },
      know: {
        min: 1
      }
    }
    const message = {
      username: {
        required: '请输入联系人'
      },
      mobile: {
        required: '请输入联系方式',
        tel: '请输入正确的手机号码'
      },
      checkInDays: {
        min: '请选择入住时间'
      },
      room_type: {
        required: '请选择房间类型'
      },
      expected_price: {
        required: '请输入期望价格',
        min: '期望价格输入有误'
      },
      street_id: {
        required: '请选择酒店地点'
      },
      star_rated: {
        required: '请选择酒店级别'
      },
      know: {
        min: '需要勾选须知才能提交'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
  },

  /**
   * 初始化数据
   * 入住时间设置时间范围/默认开始结束日期
   */
  initData: function() {
    // 入住时间数据
    const today = new Date()
    // 明天，可选择的开始时间&默认的开始时间
    const startDay = new Date(today.getTime()).toLocaleDateString()
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000).toLocaleDateString()
    // 半年后(180天后)，可选择的最晚时间
    const halfYear = new Date(today.getTime() + 24 * 60 * 60 * 1000 * 180).toLocaleDateString()
    this.setData({
      startDay,
      tomorrow,
      endDay: halfYear
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate()
    this.initData()
    this.getAddress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})